package com.example.demo.controller;

import com.example.demo.ai.NewInterviewService;
import com.example.demo.ai.model.InterviewAnalysis;
import com.example.demo.ai.model.InterviewQA;
import com.example.demo.ai.model.ResumeAnalysis;
import com.example.demo.entity.Interview;
import com.example.demo.entity.InterviewQuestion;
import com.example.demo.entity.Resume;
import com.example.demo.entity.User;
import com.example.demo.service.InterviewService;
import com.example.demo.service.ResumeService;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 新的面试功能Controller
 * 提供更简洁、高效的面试准备、开始、提交和历史记录功能
 */
@Controller
@RequestMapping("/new-interview")
public class NewInterviewController {

    @Autowired
    private InterviewService interviewService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private UserService userService;

    @Autowired
    private NewInterviewService newInterviewService;

    private static final Logger logger = LoggerFactory.getLogger(NewInterviewController.class);
    private static final String UPLOAD_DIR = "C:/uploads/";
    // 修改为无限制的问题数量
    private static final int MAX_QUESTIONS = Integer.MAX_VALUE;

    /**
     * 面试准备页面
     */
    @GetMapping("/prepare")
    public String prepareInterview(Model model) {
        model.addAttribute("resume", new Resume());
        model.addAttribute("maxQuestions", MAX_QUESTIONS);
        return "interview/prepare";
    }

    /**
     * 上传简历并创建面试
     */
    @PostMapping("/upload-resume")
    public String uploadResume(@RequestParam("file") MultipartFile file,
            @RequestParam("resumeText") String resumeText,
            @RequestParam("jobTitle") String jobTitle,
            @RequestParam(value = "jobDescription", required = false) String jobDescription,
            @RequestParam(value = "industry", required = false) String industry,
            @RequestParam(value = "difficulty", required = false, defaultValue = "2") Integer difficulty,
            Authentication authentication, Model model) {
        try {
            // 获取当前登录用户
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            logger.info("当前登录用户: {}", username);

            // 验证必填字段
            if (jobTitle == null || jobTitle.trim().isEmpty()) {
                model.addAttribute("errorMessage", "请输入预期岗位");
                model.addAttribute("maxQuestions", MAX_QUESTIONS);
                return "interview/prepare";
            }

            // 初始化简历内容变量
            String finalResumeText = resumeText;

            // 处理文件上传
            Resume resume = saveResume(file, finalResumeText, user);
            if (resume == null) {
                model.addAttribute("errorMessage", "简历保存失败");
                model.addAttribute("maxQuestions", MAX_QUESTIONS);
                return "interview/prepare";
            }

            // 创建面试记录
            Interview interview = createInterview(user, resume, jobTitle, jobDescription, industry, difficulty);
            if (interview == null) {
                model.addAttribute("errorMessage", "面试创建失败");
                model.addAttribute("maxQuestions", MAX_QUESTIONS);
                return "interview/prepare";
            }

            return "redirect:/new-interview/start?interviewId=" + interview.getId();
        } catch (Exception e) {
            logger.error("上传简历失败: {}", e.getMessage(), e);
            model.addAttribute("errorMessage", "操作失败: " + e.getMessage());
            model.addAttribute("maxQuestions", MAX_QUESTIONS);
            return "interview/prepare";
        }
    }

    /**
     * 开始面试
     */
    @GetMapping("/start")
    public String startInterview(@RequestParam("interviewId") Long interviewId, Model model) {
        try {
            logger.info("开始面试，ID: {}", interviewId);

            // 验证面试和简历信息
            Interview interview = getValidInterview(interviewId, model);
            if (interview == null) {
                return "error";
            }

            Resume resume = getValidResume(interview.getResumeId(), model);
            if (resume == null) {
                return "error";
            }

            // 只生成第一个面试问题，而不是所有问题
            String firstQuestion = generateFirstQuestion(interview, resume);
            List<String> questions = new ArrayList<>();
            questions.add(firstQuestion);

            // 分析简历内容
            ResumeAnalysis resumeAnalysis = analyzeResume(resume, interview.getJobTitle());

            // 只保存第一个问题
            saveInterviewQuestions(interviewId, questions);

            // 更新面试状态为进行中
            updateInterviewStatus(interview, 1); // 1: 进行中

            model.addAttribute("interviewId", interviewId);
            model.addAttribute("questions", questions);
            model.addAttribute("resumeAnalysis", resumeAnalysis);
            model.addAttribute("jobTitle", interview.getJobTitle());
            model.addAttribute("maxQuestions", MAX_QUESTIONS);

            logger.info("成功准备面试，ID: {}", interviewId);
            return "interview/chat";
        } catch (Exception e) {
            logger.error("启动面试时发生错误: {}", e.getMessage(), e);
            model.addAttribute("errorMessage", "启动面试时发生错误：" + e.getMessage());
            return "error";
        }
    }

    /**
     * 生成第一个面试问题
     */
    private String generateFirstQuestion(Interview interview, Resume resume) {
        try {
            // 调用NewInterviewService的generateSingleQuestion方法生成第一个问题
            List<String> previousQuestions = new ArrayList<>(); // 没有之前的问题
            return newInterviewService.generateSingleQuestion(
                    resume.getResumeText(),
                    interview.getJobTitle(),
                    interview.getJobDescription(),
                    interview.getIndustry(),
                    interview.getDifficulty(),
                    previousQuestions
            );
        } catch (Exception e) {
            logger.error("生成第一个问题失败: {}", e.getMessage());
            // 使用默认问题
            return "请简单介绍一下你自己。";
        }
    }

    /**
     * 提交面试答案并获取分析结果
     */
    @GetMapping("/submit-answers")
    @PostMapping("/submit-answers")
    public String submitAnswers(@RequestParam("interviewId") Long interviewId,
            @RequestParam(required = false) Map<String, String> answers,
            Model model) {
        try {
            // 验证面试和简历信息
            Interview interview = getValidInterview(interviewId, model);
            if (interview == null) {
                return "error";
            }

            Resume resume = getValidResume(interview.getResumeId(), model);
            if (resume == null) {
                return "error";
            }

            // 获取问题列表并更新答案
            List<InterviewQuestion> questions = interviewService.findQuestionsByInterviewId(interviewId);
            List<InterviewQA> qaList = updateAnswers(questions, answers);

            // 分析面试答案
            InterviewAnalysis analysis = analyzeInterview(interview, resume, qaList);

            // 生成示例答案
            List<InterviewQA> exampleQAs = generateExampleAnswers(resume, qaList, interview.getJobTitle());

            // 更新面试状态为已完成
            updateInterviewResult(interview, analysis, 2); // 2: 已完成

            model.addAttribute("interview", interview);
            model.addAttribute("questions", questions);
            model.addAttribute("analysis", analysis);
            model.addAttribute("qas", qaList);
            model.addAttribute("exampleQAs", exampleQAs);
            model.addAttribute("maxQuestions", MAX_QUESTIONS);
            
            // 分析简历内容，添加到模型中以便在结果页面显示
            ResumeAnalysis resumeAnalysis = analyzeResume(resume, interview.getJobTitle());
            model.addAttribute("resumeAnalysis", resumeAnalysis);
            return "interview/result";
        } catch (Exception e) {
            logger.error("提交回答失败: {}", e.getMessage(), e);
            model.addAttribute("errorMessage", "提交回答失败");
            model.addAttribute("interviewId", interviewId);
            return "redirect:/new-interview/start?interviewId=" + interviewId;
        }
    }

    /**
     * 生成下一个面试问题（AJAX接口）- 支持上下文相关的问题生成
     */
    @PostMapping("/generate-next-question")
    @ResponseBody
    public ResponseEntity<?> generateNextQuestion(@RequestParam Long interviewId,
            @RequestParam Integer currentQuestionIndex) {
        try {
            // 验证面试和简历信息
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                return ResponseEntity.badRequest().body("面试不存在");
            }

            Resume resume = resumeService.findById(interview.getResumeId());
            if (resume == null) {
                return ResponseEntity.badRequest().body("简历不存在");
            }

            // 查询当前面试已有的问题
            List<InterviewQuestion> existingQuestions = interviewService.findQuestionsByInterviewId(interviewId);
            List<String> previousQuestions = existingQuestions.stream()
                    .map(InterviewQuestion::getQuestion)
                    .collect(Collectors.toList());

            // 移除最大问题数量限制，允许生成任意数量的问题
            
            // 移除必须回答当前问题的限制，允许用户跳过问题

            // 生成新问题 - 优先使用带上下文的生成方式
            String newQuestion;
            if (currentQuestionIndex >= 0 && currentQuestionIndex < existingQuestions.size()) {
                // 创建QA列表作为上下文
                List<InterviewQA> qaContext = new ArrayList<>();
                for (int i = 0; i <= currentQuestionIndex; i++) {
                    InterviewQuestion question = existingQuestions.get(i);
                    InterviewQA qa = new InterviewQA();
                    qa.setQuestion(question.getQuestion());
                    qa.setAnswer(question.getUserAnswer());
                    qaContext.add(qa);
                }
                
                // 使用带上下文的方式生成新问题
                logger.debug("使用带上下文的方式生成问题，当前问题索引: {}", currentQuestionIndex);
                newQuestion = newInterviewService.generateSingleQuestionWithContext(
                        resume.getResumeText(),
                        interview.getJobTitle(),
                        interview.getJobDescription(),
                        interview.getIndustry(),
                        interview.getDifficulty(),
                        qaContext);
            } else {
                // 使用不带上下文的方式生成问题
                logger.debug("使用不带上下文的方式生成问题");
                newQuestion = newInterviewService.generateSingleQuestion(
                        resume.getResumeText(),
                        interview.getJobTitle(),
                        interview.getJobDescription(),
                        interview.getIndustry(),
                        interview.getDifficulty(),
                        previousQuestions);
            }

            // 保存新问题
            saveSingleQuestion(interviewId, newQuestion, existingQuestions.size() + 1);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("question", newQuestion);
            result.put("questionIndex", existingQuestions.size()); // 前端从0开始
            result.put("totalQuestions", existingQuestions.size() + 1); // 当前总问题数
            result.put("maxQuestions", Integer.MAX_VALUE); // 设为最大值，表示无限制

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("生成下一个问题失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("生成问题失败: " + e.getMessage());
        }
    }

    /**
     * 保存单个问题的答案（AJAX接口）
     */
    @PostMapping("/save-answer")
    @ResponseBody
    public ResponseEntity<?> saveAnswer(@RequestParam Long interviewId,
            @RequestParam Integer questionIndex,
            @RequestBody String answer) {
        try {
            // 验证面试信息
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                return ResponseEntity.badRequest().body("面试不存在");
            }

            // 查询对应序号的问题
            List<InterviewQuestion> questions = interviewService.findQuestionsByInterviewId(interviewId);
            if (questionIndex < 0 || questionIndex >= questions.size()) {
                return ResponseEntity.badRequest().body("问题索引无效");
            }

            // 更新答案
            InterviewQuestion question = questions.get(questionIndex);
            question.setUserAnswer(answer);
            interviewService.saveQuestion(question);

            // 获取面试进度
            int answeredCount = (int) questions.stream()
                    .filter(q -> q.getUserAnswer() != null && !q.getUserAnswer().trim().isEmpty())
                    .count();
            int totalCount = questions.size();
            int progressPercentage = (int) ((double) answeredCount / totalCount * 100);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "答案保存成功");
            result.put("answeredCount", answeredCount);
            result.put("totalCount", totalCount);
            result.put("progressPercentage", progressPercentage);
            result.put("maxQuestions", MAX_QUESTIONS);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("保存答案失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("保存答案失败: " + e.getMessage());
        }
    }

    /**
     * 获取面试进度（新增AJAX接口）
     */
    @GetMapping("/progress")
    @ResponseBody
    public ResponseEntity<?> getProgress(@RequestParam Long interviewId) {
        try {
            // 验证面试信息
            Interview interview = interviewService.findById(interviewId);
            if (interview == null) {
                return ResponseEntity.badRequest().body("面试不存在");
            }

            // 查询问题列表
            List<InterviewQuestion> questions = interviewService.findQuestionsByInterviewId(interviewId);
            if (questions == null || questions.isEmpty()) {
                return ResponseEntity.badRequest().body("面试问题不存在");
            }

            // 计算已回答的问题数量
            int answeredCount = (int) questions.stream()
                    .filter(q -> q.getUserAnswer() != null && !q.getUserAnswer().trim().isEmpty())
                    .count();

            int totalCount = questions.size();
            int progressPercentage = (int) ((double) answeredCount / totalCount * 100);
            boolean isCompleted = (answeredCount == totalCount);
            Integer currentQuestionIndex = null;
            
            // 查找下一个未回答的问题索引
            for (int i = 0; i < questions.size(); i++) {
                InterviewQuestion question = questions.get(i);
                if (question.getUserAnswer() == null || question.getUserAnswer().trim().isEmpty()) {
                    currentQuestionIndex = i;
                    break;
                }
            }
            
            // 如果所有问题都已回答，当前索引就是最后一个问题
            if (currentQuestionIndex == null) {
                currentQuestionIndex = questions.size() - 1;
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("answeredCount", answeredCount);
            result.put("totalCount", totalCount);
            result.put("progressPercentage", progressPercentage);
            result.put("currentQuestionIndex", currentQuestionIndex);
            result.put("isCompleted", isCompleted);
            result.put("maxQuestions", MAX_QUESTIONS);

            logger.debug("获取面试进度，ID: {}, 进度: {}/{} ({}%)", 
                    interviewId, answeredCount, totalCount, progressPercentage);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取面试进度失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取进度失败: " + e.getMessage());
        }
    }

    /**
     * 面试历史记录
     */
    @GetMapping("/history")
    public String interviewHistory(Authentication authentication, Model model) {
        try {
            // 获取当前登录用户的所有面试记录
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            List<Interview> interviews = interviewService.findByUserId(user.getId());

            // 按创建时间倒序排序
            interviews.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));

            // 计算统计数据
            if (!interviews.isEmpty()) {
                // 计算平均评分
                double avgScore = interviews.stream()
                        .filter(interview -> interview.getOverallScore() != null)
                        .mapToDouble(Interview::getOverallScore)
                        .average()
                        .orElse(0.0);

                // 获取最高评分
                double highestScore = interviews.stream()
                        .filter(interview -> interview.getOverallScore() != null)
                        .mapToDouble(Interview::getOverallScore)
                        .max()
                        .orElse(0.0);

                // 获取最近面试日期
                String lastInterviewDate = interviews.stream()
                        .max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime()))
                        .map(interview -> interview.getCreateTime()
                                .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .orElse("");

                model.addAttribute("avgScore", avgScore);
                model.addAttribute("highestScore", highestScore);
                model.addAttribute("lastInterviewDate", lastInterviewDate);
            }

            model.addAttribute("interviews", interviews);
            model.addAttribute("maxQuestions", MAX_QUESTIONS);
            return "interview/history";
        } catch (Exception e) {
            logger.error("获取面试历史失败: {}", e.getMessage(), e);
            model.addAttribute("errorMessage", "获取面试历史失败");
            return "error";
        }
    }

    /**
     * 面试详情
     */
    @GetMapping("/detail")
    public String interviewDetail(@RequestParam("interviewId") Long interviewId, Model model) {
        try {
            // 验证面试信息
            Interview interview = getValidInterview(interviewId, model);
            if (interview == null) {
                return "error";
            }

            // 获取面试问题
            List<InterviewQuestion> questions = interviewService.findQuestionsByInterviewId(interviewId);

            // 如果有简历分析，添加到模型中
            Resume resume = resumeService.findById(interview.getResumeId());
            if (resume != null) {
                try {
                    ResumeAnalysis resumeAnalysis = newInterviewService.analyzeResume(resume.getResumeText(),
                            interview.getJobTitle());
                    model.addAttribute("resumeAnalysis", resumeAnalysis);
                } catch (Exception e) {
                    logger.warn("获取简历分析失败: {}", e.getMessage());
                }
            }

            model.addAttribute("interview", interview);
            model.addAttribute("questions", questions);
            model.addAttribute("maxQuestions", MAX_QUESTIONS);
            return "interview/detail";
        } catch (Exception e) {
            logger.error("获取面试详情失败: {}", e.getMessage(), e);
            model.addAttribute("errorMessage", "获取面试详情失败");
            return "error";
        }
    }

    // 以下是辅助方法

    /**
     * 保存简历
     */
    private Resume saveResume(MultipartFile file, String resumeText, User user) throws IOException {
        try {
            Resume resume = new Resume();
            resume.setUserId(user.getId());
            resume.setResumeText(resumeText);

            // 处理文件上传（如果有文件）
            if (file != null && !file.isEmpty()) {
                // 确保上传目录存在
                File uploadDir = new File(UPLOAD_DIR);
                if (!uploadDir.exists()) {
                    boolean created = uploadDir.mkdirs();
                    logger.info("上传目录创建结果: {}", created);
                }

                // 生成唯一文件名
                String filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                String filePath = UPLOAD_DIR + filename;

                // 保存文件
                file.transferTo(new File(filePath));

                // 设置文件信息
                resume.setFileName(filename);
                resume.setFilePath(filePath);
            }

            // 保存简历信息
            boolean resumeSaved = resumeService.save(resume);
            logger.info("简历保存结果: {}", resumeSaved);

            return resumeSaved ? resume : null;
        } catch (IOException e) {
            logger.error("文件上传失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 创建面试记录
     */
    private Interview createInterview(User user, Resume resume, String jobTitle,
            String jobDescription, String industry, Integer difficulty) {
        Interview interview = new Interview();
        interview.setUserId(user.getId());
        interview.setResumeId(resume.getId());
        interview.setJobTitle(jobTitle);
        interview.setJobDescription(jobDescription);
        interview.setIndustry(industry);
        interview.setDifficulty(difficulty);
        interview.setStatus(0); // 未开始
        interview.setCreateTime(LocalDateTime.now());
        interview.setUpdateTime(LocalDateTime.now());

        boolean interviewSaved = interviewService.save(interview);
        logger.info("面试记录保存结果: {}", interviewSaved);

        return interviewSaved ? interview : null;
    }

    /**
     * 获取有效的面试信息
     */
    private Interview getValidInterview(Long interviewId, Model model) {
        Interview interview = interviewService.findById(interviewId);
        if (interview == null) {
            logger.error("面试不存在，ID: {}", interviewId);
            model.addAttribute("errorMessage", "面试不存在");
            return null;
        }
        return interview;
    }

    /**
     * 获取有效的简历信息
     */
    private Resume getValidResume(Long resumeId, Model model) {
        Resume resume = resumeService.findById(resumeId);
        if (resume == null) {
            logger.error("简历不存在");
            model.addAttribute("errorMessage", "简历不存在");
            return null;
        }
        return resume;
    }

    /**
     * 生成面试问题
     */
    private List<String> generateInterviewQuestions(Interview interview, Resume resume) {
        try {
            return newInterviewService.generateInterviewQuestions(
                    resume.getResumeText(),
                    interview.getJobTitle(),
                    interview.getJobDescription(),
                    interview.getIndustry(),
                    interview.getDifficulty(),
                    MAX_QUESTIONS // 使用常量而不是硬编码的5
            );
        } catch (Exception e) {
            logger.error("生成面试问题失败: {}", e.getMessage());
            // 使用默认问题
            return Arrays.asList(
                    "请简单介绍一下你自己。",
                    "你为什么对这个职位感兴趣？",
                    "你最大的优势是什么？",
                    "你认为自己需要改进的地方是什么？",
                    "你对我们公司有什么了解？");
        }
    }

    /**
     * 分析简历
     */
    private ResumeAnalysis analyzeResume(Resume resume, String jobTitle) {
        try {
            return newInterviewService.analyzeResume(resume.getResumeText(), jobTitle);
        } catch (Exception e) {
            logger.error("分析简历失败: {}", e.getMessage());
            // 创建默认的简历分析结果
            ResumeAnalysis resumeAnalysis = new ResumeAnalysis();
            resumeAnalysis.setScore(80.0);
            resumeAnalysis.setSummary("您的简历基本符合要求，包含了必要的个人信息和工作经历。");
            resumeAnalysis.setStrengths("简历结构清晰，工作经历连贯。");
            resumeAnalysis.setAreasForImprovement("可以更突出个人成就和专业技能。");
            resumeAnalysis.setSuggestions("1. 量化工作成果 2. 突出与目标职位相关的技能 3. 优化简历结构");
            resumeAnalysis.setFormattingTips("使用清晰的标题层级，保持一致的格式，控制简历长度在1-2页。");
            return resumeAnalysis;
        }
    }

    /**
     * 保存面试问题
     */
    private void saveInterviewQuestions(Long interviewId, List<String> questions) {
        for (int i = 0; i < questions.size(); i++) {
            InterviewQuestion question = new InterviewQuestion();
            question.setInterviewId(interviewId);
            question.setQuestion(questions.get(i));
            question.setOrderNumber(i + 1);
            interviewService.saveQuestion(question);
        }
    }

    /**
     * 保存单个问题
     */
    private void saveSingleQuestion(Long interviewId, String question, Integer orderNumber) {
        InterviewQuestion interviewQuestion = new InterviewQuestion();
        interviewQuestion.setInterviewId(interviewId);
        interviewQuestion.setQuestion(question);
        interviewQuestion.setOrderNumber(orderNumber);
        interviewService.saveQuestion(interviewQuestion);
    }

    /**
     * 更新面试状态
     */
    private void updateInterviewStatus(Interview interview, Integer status) {
        interview.setStatus(status);
        if (status == 1) { // 进行中
            interview.setStartTime(LocalDateTime.now());
        } else if (status == 2) { // 已完成
            interview.setEndTime(LocalDateTime.now());
        }
        interview.setUpdateTime(LocalDateTime.now());
        interviewService.update(interview);
    }

    /**
     * 更新问题答案
     */
    private List<InterviewQA> updateAnswers(List<InterviewQuestion> questions, Map<String, String> answers) {
        List<InterviewQA> qaList = new ArrayList<>();
        for (int i = 0; i < questions.size(); i++) {
            InterviewQuestion question = questions.get(i);
            // 尝试通过索引获取答案
            String answer = answers.get("answer_" + i);

            // 如果没找到，尝试通过ID获取答案
            if (answer == null) {
                answer = answers.get("answer_" + question.getId());
            }

            // 更新问题答案
            question.setUserAnswer(answer);
            interviewService.saveQuestion(question);

            // 创建QA对象
            InterviewQA qa = new InterviewQA();
            qa.setQuestion(question.getQuestion());
            qa.setAnswer(answer);
            qaList.add(qa);
        }
        return qaList;
    }

    /**
     * 分析面试答案
     */
    private InterviewAnalysis analyzeInterview(Interview interview, Resume resume, List<InterviewQA> qaList) {
        try {
            return newInterviewService.analyzeInterviewAnswers(
                    resume.getResumeText(),
                    qaList,
                    interview.getJobTitle());
        } catch (Exception e) {
            logger.error("分析面试答案失败: {}", e.getMessage());
            // 返回默认分析结果
            InterviewAnalysis analysis = new InterviewAnalysis();
            analysis.setScore(75.0);
            analysis.setSuggestion("您的面试表现基本符合要求，有一定的专业基础。");
            analysis.setStrengths(Arrays.asList("沟通能力良好", "专业知识扎实"));
            analysis.setAreasForImprovement(Arrays.asList("可以更详细地描述项目经验", "加强技术深度"));
            return analysis;
        }
    }

    /**
     * 生成示例答案
     */
    private List<InterviewQA> generateExampleAnswers(Resume resume, List<InterviewQA> qaList, String jobTitle) {
        try {
            return newInterviewService.generateExampleAnswers(resume.getResumeText(), qaList, jobTitle);
        } catch (Exception e) {
            logger.error("生成示例答案失败: {}", e.getMessage());
            // 返回基于问题的默认示例答案
            List<InterviewQA> exampleQAs = new ArrayList<>();
            for (InterviewQA qa : qaList) {
                InterviewQA exampleQA = new InterviewQA();
                exampleQA.setQuestion(qa.getQuestion());
                exampleQA.setAnswer("这是一个很好的问题。根据我的经验和理解，我认为最佳的做法是...");
                exampleQAs.add(exampleQA);
            }
            return exampleQAs;
        }
    }

    /**
     * 更新面试结果
     */
    private void updateInterviewResult(Interview interview, InterviewAnalysis analysis, Integer status) {
        interview.setStatus(status);
        interview.setOverallScore(analysis.getScore());
        interview.setSummary(analysis.getSuggestion());
        // 将列表转换为逗号分隔的字符串
        if (analysis.getStrengths() != null && !analysis.getStrengths().isEmpty()) {
            interview.setStrengths(String.join("，", analysis.getStrengths()));
        }
        if (analysis.getAreasForImprovement() != null && !analysis.getAreasForImprovement().isEmpty()) {
            interview.setImprovements(String.join("，", analysis.getAreasForImprovement()));
        }
        interview.setUpdateTime(LocalDateTime.now());
        interview.setEndTime(LocalDateTime.now());
        interviewService.update(interview);
    }
}